import React from 'react'
import { bindActionCreators } from 'redux'
import * as reviewAction from '../../actions/review.action'
import { connect } from 'react-redux'
import style from './style'
import cx from 'classnames'
import { info, Modal, Link, TitleBar, Table, Button, success as successToast,error as errorToast, DateSelect, Tooltip } from '../../ui-components'
import DatePicker from 'react-date-picker'
import { reduxForm } from 'redux-form'
import util from '../../util'
import moment from 'moment'
moment.locale('zh-cn')
var ReactTooltip = require("react-tooltip")

/**
 * 日期组件
 * @todo 移动至ui-component 
 * @todo 换个好看点儿的~
 */
class DateInput extends React.Component {
  state = {
    showDatePicker: false,
    cancelReviewActivity: false,
    deleteQuestion: false
  }
  closeDatePicker = () => {
    this.setState({
      showDatePicker: false
    })
    util.unbind(document, 'click', this.closeDatePicker)
  }

  handleClick = (e) => {
    let el = e.target
    while(true) {
      if (!el || el == document.body) {
        util.unbind(document, 'click', this.handleClick)
        this.setState({
          showDatePicker: false
        })
        break
      }
      if (el && ~el.className.indexOf('date-picker'))  {
        break
      }
      el = el.parentNode
    }
  }
  handleFocus(e) {
    e.stopPropagation()
    util.bind(document, 'click', this.handleClick)
    this.setState({
      showDatePicker: true
    })
  }
  handleChange(e){
    if( ! this.props.validChange || (this.props.validChange && this.props.validChange(e.target.value))){
      const value = this.stringToStamp(e.target.value)
      this.props.onChange(value)
    }
  }
  handlePickerChange(time, m){
    if( ! this.props.validChange || (this.props.validChange && this.props.validChange(m.valueOf()))){
      this.setState({
        time
      })
      this.props.onChange(m.valueOf()+24*60*60*1000-1)
      setTimeout(() => {
        this.setState({
          showDatePicker: false
        })
      }, 150)
    }
  }
  stringToStamp(timeString){
    const stamp = new Date(timeString).getTime()
    return stamp
  }
  stampToString(stamp){
    const timeString = stamp ? moment(parseInt(stamp)).format('YYYY-MM-DD') : ''
    return timeString
  }
  render(){
    return (
      <div style={{display:'inline-block', position:'relative'}}>
        <input
          className={style.date_input}
          value={this.stampToString(this.props.value)}
          onChange={::this.handleChange}
          placeholder={this.props.placeholder}
          onClick={::this.handleFocus}
          data-tip={this.props['data-tip']}
        />
        {
          this.state.showDatePicker? (
            <DatePicker 
              style={{
                width: '254px',
                height: '254px',
                position: 'absolute',
                zIndex: '99'
              }}
              onChange={::this.handlePickerChange}
              className={style.datePicker}
              hideFooter={true} 
              date={this.props.value}
            />
          ): null
        }
      </div>
    )
  }
}

/**
 *  反馈活动表单模板
 */
class TemplateForm extends React.Component { 
  state = {
    newQuestions: [],
    newQuestion: '',
    deleteQuestion: false
  }
  componentDidMount() {
    if (this.props.fields.questions.initialValue && this.props.fields.questions.initialValue.length) {
      this.setState({
        newQuestions: this.props.fields.questions.initialValue,
      })
    } else {
      console.log('请传入 questions 的 initialValue')
    }
  }
  addQuestion(){
    if (!!this.refs.newQuestion.value) {
      this.state.newQuestions.push(this.refs.newQuestion.value)
      this.setState({
        newQuestions: this.state.newQuestions
      })
    }
    this.refs.newQuestion.value = ''
  }
  removeQuestion(i){
    this.setState({
      deleteQuestion: true,
      readyDeletedQuestion: i
    })
  }

  deleteQuestion() {
    this.state.newQuestions.splice(this.state.readyDeletedQuestion,1)
    this.setState({
      newQuestions: this.state.newQuestions,
      deleteQuestion: false
    })
  }

  render(){
    const {fields: {templateId, templateName, startTime, endTime, selfReviewDeadline, peerReviewDeadline, publicDeadline, questions}, handleSubmit} = this.props;
    return (
      <div className={style.template_form}>
        <div>
          <label>名称{this.state.templateName}</label>
          <div>
            <input type="text" {...templateName} />
          </div>
        </div>
        <div>
          <label>工作阶段<Tooltip tip="本次反馈活动所针对的工作阶段。<br />例如，针对 2016 年 Q1 的工作进行反馈，<br />则工作阶段为 2016-04-01 到 2016-07-01" /></label>
          <div>
            <DateInput {...startTime} validChange={(value)=>{
              if (!!this.props.fields.endTime.value && value >= this.props.fields.endTime.value) {
                errorToast('工作阶段开始日期应早于结束日期')
                return false
              } else if (value > Date.now()){
                errorToast('工作阶段开始日期不能晚于今日')
                return false
              } else {
                return true
              }
            }} />
           　 到 　
            <DateInput {...endTime} validChange={(value)=>{
              if (value <= this.props.fields.startTime.value) {
                errorToast('工作阶段结束日期应晚于开始日期')
                return false
              } else if (value > Date.now()){
                errorToast('工作阶段结束日期不能晚于今日')
                return false
              } else if (!!this.props.fields.selfReviewDeadline.value && value >= this.props.fields.selfReviewDeadline.value){
                errorToast('工作阶段结束日期不能晚于自评截止日')
                return false
              } else {
                return true
              }
            }} />
          </div>
        </div>
        <div>
          <label>自评截止日<Tooltip tip="员工需要在此日期前提交自评" /></label>
          <div><DateInput {...selfReviewDeadline} validChange={(value)=>{
              if (value <= Date.now()) {
                errorToast('自评截止日应晚于今日')
                return false
              }else if (value <= this.props.fields.endTime.value) {
                errorToast('自评截止日应晚于工作阶段结束日期')
                return false
              } else if (value <= Date.now()){
                errorToast('自评截止日必须晚于今日')
                return false
              } else if (!!this.props.fields.peerReviewDeadline.value && value >= this.props.fields.peerReviewDeadline.value){
                errorToast('自评截止日不能晚于同事反馈截止日')
                return false
              } else {
                return true
              }
            }} />
          </div>
        </div>
        <div>
          <label>同事反馈截止日<Tooltip tip="员工需要在此日期前提交同事反馈" /></label>
          <div> <DateInput {...peerReviewDeadline} validChange={(value)=>{
              if (value <= this.props.fields.selfReviewDeadline.value) {
                errorToast('同事反馈截止日应晚于自评截止日')
                return false
              } else if (!!this.props.fields.publicDeadline.value && value >= this.props.fields.publicDeadline.value){
                errorToast('同事反馈截止日不能晚于流程结束时间')
                return false
              } else {
                return true
              }
            }} /></div>
        </div>
        <div>
          <label>流程结束<Tooltip tip="流程结束后，员工将能看到所有人对自己的反馈" /></label>
          <div> <DateInput {...publicDeadline} validChange={(value)=>{
              if (value <= this.props.fields.peerReviewDeadline.value) {
                errorToast('流程结束时间应晚于同事反馈截止日')
                return false
              } else {
                return true
              }
            }} /></div>
        </div>
        <div>
          <label>通用问题<Tooltip tip="反馈活动中，要求全部员工都回答的问题" /></label>
          <div>
          {
            this.state.newQuestions.map((v, i)=> (
              <p key={i} className={style.question}>
                {v}
                <i 
                  className={style.delete} 
                  onClick={() => this.removeQuestion(i)}
                >
                  删除
                </i>
              </p>
              )
            )
          }
            <input ref="newQuestion" type="text" />
            <Button
              className={style.btn_addquestion} 
              label="添加"
              green
              onClick={::this.addQuestion}
            />
          </div>
        </div>
        <Modal
          onRequestClose={() => this.setState({ deleteQuestion: false })}
          active={this.state.deleteQuestion}
          actions={[
            'cancel',
            ::this.deleteQuestion
          ]}
          title="删除问题"
        >
          <div>确认删除此问题？</div>
        </Modal>
      </div>
    )
  }
}
TemplateForm = reduxForm({
    form: 'TemplateForm', // a unique name for this form
    fields: ['templateId', 'templateName', 'startTime', 'endTime', 'selfReviewDeadline', 'peerReviewDeadline', 'publicDeadline', 'questions']
  }
)(TemplateForm);




/**
 * 反馈活动模板
 * @todo 切换动画
 * @param  {[type]} dispatch [description]
 * @return {[type]}          [description]
 */
@connect(null, dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class TemplateBlock extends React.Component {
  state = {
    isEditing: false
  }
  editTemplate(){
    this.setState({
      isEditing: true
    })
  }
  handleSubmit() {
    this.setState({isEditing: !this.refs.templateForm.submit()}) //submit返回校验 
  }
  handlePublish() {
    const {
      templateId=null,
      selfReviewDeadline,
    } = this.props.data
    if (selfReviewDeadline <= Date.now()) {
      errorToast('自评截止日应晚于今日')
      return false;
    }
    this.props.actions.publishReviewTemplate(templateId, () => {
      successToast('发布成功！')
      this.props.actions.fetchReviewTemplates()
    })
  }
  saveTemplate(data){
    console.log(data);
    //@todo 表单返回校验结果  重构form表单，校验一体
    if (! data.templateName) {
      errorToast('请填写活动名称')
      return false
    } else if (data.templateName.length > 20) {
      errorToast('活动名称不能超过 20 个字')
      return false
    } else if (! data.startTime || ! data.endTime) {
      errorToast('请完整填写工作阶段')
      return false
    } else if (! data.selfReviewDeadline) {
      errorToast('请填写自评截止日')
      return false
    } else if (! data.peerReviewDeadline) {
      errorToast('请填写同事反馈截止日')
      return false
    } else if (! data.publicDeadline) {
      errorToast('请填写流程结束时间')
      return false
    } else if (data.questions.length < 1) {
      errorToast('请至少填写一个公共问题')
      return false
    }
    const {
      templateId = null,
      selfReviewDeadline,
    } = data
    if (selfReviewDeadline <= Date.now()) {
      errorToast('自评截止日应晚于今日')
      return false;
    }
    if (templateId) {
      this.props.actions.updateTemplate(data, () => {
        this.props.actions.fetchReviewTemplates()
      })
      return true;
    } else {
      return false;
    }
  }
  cancelTemplate(){
    const {templateId=null} = this.props.data
    if (templateId) {
      this.setState({
        cancelReviewActivity: true
      })
    }
  }

  cancelReviewActivity() {
    const {templateId=null} = this.props.data
    info('取消中...')
    this.props.actions.cancelReviewTemplate(templateId, () => {
      successToast('反馈活动已取消，未提交的反馈将自动备份发送到员工邮箱')
      this.props.actions.fetchReviewTemplates()
    })
    this.setState({
      cancelReviewActivity: false
    })
  }

  render() {
    const v = this.props.data
    const {questions=[]} = v
    return (
      <div className={cx({
        [style.item]:true,
        [style.editing]:this.state.isEditing})}>
        {
          this.state.isEditing ? (
            <div>
              <TemplateForm ref="templateForm" formKey={this.props.formKey.toString()} initialValues={util.deepClone(v)} onSubmit={::this.saveTemplate} />
              <div className={style.operate}>
                <Button label="保存" onClick={::this.handleSubmit} /> 
                <Link onClick={() => this.setState({isEditing: false})} label="取消" />
              </div>
            </div>
            ) : (
            <div>
              <h2>{v.templateName}</h2>
              <div className={cx({[style.state]: true, [style['color' + v.state]]: true})}>{META_TEMPLATE_STATE[v.state]}</div>
              <div className={style.template_block}>
                <div>
                  <label>工作阶段</label>
                  <div>
                  {
                    moment(v.startTime).format('YYYY.MM.DD') + '~' + moment(v.endTime).format('YYYY.MM.DD')
                  }
                  </div>
                </div>
                <div>
                  <label>自评截止日</label>
                  <div>
                  {
                    moment(v.selfReviewDeadline).format('YYYY.MM.DD')
                  }
                  </div>
                </div>
                <div>
                  <label>同事反馈截止日</label>
                  <div>
                  {
                    moment(v.peerReviewDeadline).format('YYYY.MM.DD')
                  }
                  </div>
                </div>
                <div>
                  <label>流程结束</label>
                  <div>
                  {
                    moment(v.publicDeadline).format('YYYY.MM.DD')
                  }
                  </div>
                </div>
                <div>
                  <label>通用问题</label>
                  <div>
                    {
                      questions.map((v, i) => <p key={i}>- {v}</p>)
                    }
                  </div>
                </div>
                {
                  v.state != 4 ?  <div>
                      <div className={style.operate} colspan="2">
                        {
                          v.state == 1 ? <Button className={style.btn_operate} label="发布" onClick={::this.handlePublish}/> : null
                        }
                        {
                          v.state == 2 || v.state == 3 ? <Link label="查看报告" to={`#/review/report/${v.templateId}`}/> : null
                        }
                        {
                          v.state == 2 ? <Link onClick={() => this.cancelTemplate()} color="red" label="取消活动"/> : null
                        }
                        {
                          v.state == 1 ? <Link onClick={() => this.editTemplate()} label="编辑"/> : null
                        }
                      </div>
                    </div> : null
                }
              </div>
            </div>
          )
        }
        <Modal
          onRequestClose={() => this.setState({ cancelReviewActivity: false })}
          active={this.state.cancelReviewActivity}
          actions={[
            'cancel',
            ::this.cancelReviewActivity
          ]}
          title="取消该反馈活动"
        >
          <div>确定取消该反馈活动？</div>
        </Modal>
      </div>
    )
  }
}


/**
 * @todo 问题模板放到constants中
 */
export default
@connect(({ review }) => ({ review }), dispatch => ({actions: bindActionCreators({...reviewAction}, dispatch)}))
class ReviewAdmin extends React.Component {
  state = {
    isShowCreateForm: false
  }

  componentDidMount() {
    this.props.actions.fetchReviewTemplates()
  }

  handleNewTeamplateSubmit(data) {
    if (! data.templateName) {
      errorToast('请填写活动名称')
      return false
    } else if (data.templateName.length > 20) {
      errorToast('活动名称不能超过 20 个字')
      return false
    } else if (! data.startTime || ! data.endTime) {
      errorToast('请完整填写工作阶段')
      return false
    } else if (! data.selfReviewDeadline) {
      errorToast('请填写自评截止日')
      return false
    } else if (! data.peerReviewDeadline) {
      errorToast('请填写同事反馈截止日')
      return false
    } else if (! data.publicDeadline) {
      errorToast('请填写流程结束时间')
      return false
    } else if (data.questions.length < 1) {
      errorToast('请至少填写一个公共问题')
      return false
    }
    this.props.actions.createTemplate(data, () => {
      console.log(arguments);
      this.setState({
        isShowCreateForm: false
      })
    })
  }
  saveTemplate(templateId=null){
    this.refs.addTemplate.submit()
  }
  render() {
    const{ templates: {reviewTemplates, amount} } = this.props.review
    let actions = [
      {
        label: '新增活动',
        handler: () => this.setState({isShowCreateForm: true})
      }
    ]
    return (
      <div>
        <TitleBar label="反馈活动管理" actions={actions} />
        <div className={style.templates}>
        {
          this.state.isShowCreateForm ? (
              <div className={style.creator}>
                <TemplateForm ref="addTemplate" initialValues={{questions:['有哪些地方你觉得自己做得不错，并且打算继续保持？','有哪些地方有待改进？']}} onSubmit={::this.handleNewTeamplateSubmit} />
                <div className={style.operate} colspan="2">
                  <Button className={style.btn_operate} label="保存草稿，继续下一步" onClick={::this.saveTemplate} />
                  <Button className={style.btn_operate} white label="取消" onClick={() => this.setState({isShowCreateForm: false})} />
                </div>
              </div>) : null
        }
        {
          reviewTemplates && reviewTemplates.length ? (
            <div className="templateList">
              {
                reviewTemplates.map((v, i)=>{
                    return <TemplateBlock key={i} formKey={i} data={v} />
                  }
                )
              }
            </div>
          ) : 
          this.state.isShowCreateForm ? null :
          (
            <div style={{ top: '182px', position: 'absolute', left: '50%', marginLeft: '-100px', textAlign: "center", width: "200px", "zIndex": -1 }}>
              <img width="140" height="140" src={`/${util.getImagePath()}/default/review.png`}/>
              <div style={{ marginTop: '20px', fontSize: '18px', color: '#999' }}>没有找到相关数据</div>
            </div>
          )
        }
        </div>
      </div>
    )
  }
}
